In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.
Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.
In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing the code template and writeup template will cover all of the rubric points for this project.
The rubric contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.
Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.
# Load pickled data
import pickle
# TODO: Fill this in based on where you saved the training and testing data
training_file = "data/train.p"
validation_file = "data/valid.p"
testing_file = "data/test.p"
with open(training_file, mode='rb') as f:
train = pickle.load(f)
with open(validation_file, mode='rb') as f:
valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
test = pickle.load(f)
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test = test['features'], test['labels']
The pickled data is a dictionary with 4 key/value pairs:
'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.'sizes' is a list containing tuples, (width, height) representing the original width and height the image.'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGESComplete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the pandas shape method might be useful for calculating some of the summary results.
### Replace each question mark with the appropriate value.
### Use python, pandas or numpy methods rather than hard coding the results
# TODO: Number of training examples
n_train = X_train.shape[0]
# TODO: Number of validation examples
n_validation = X_valid.shape[0]
# TODO: Number of testing examples.
n_test =X_test.shape[0]
# TODO: What's the shape of an traffic sign image?
image_shape = X_train[0].shape
# TODO: How many unique classes/labels there are in the dataset.
n_classes = len(set(y_train)) #https://stackoverflow.com/a/12282286
print("Number of training examples =", n_train)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
Number of training examples = 34799 Number of testing examples = 12630 Image data shape = (32, 32, 3) Number of classes = 43
Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.
The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.
NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections. It can be interesting to look at the distribution of classes in the training, validation and test set. Is the distribution the same? Are there more examples of some classes than others?
### Data exploration visualization code goes here.
### Feel free to use as many code cells as needed.
import matplotlib.pyplot as plt
# Visualizations will be shown in the notebook.
%matplotlib inline
import random
import pandas as pd
import numpy as np
import textwrap
from PIL import Image
from os import listdir
from os.path import isfile, join, basename
Classes to help in exploring and viewing data:
random.seed()
class Logger:
'''
Simple logger for project to make output messages look clean"
'''
def __init__(self, name, owner=None):
if owner is not None:
# https://stackoverflow.com/a/7983848
name = name + "-" + str(id(owner))[-4:]
self.name = name
return
def log(self, msg):
print (self.name + " | " + msg)
return
class SignNames_CSV:
'''
Provides access to the signnames.csv to retrieve sign names.
'''
def __init__(self):
self.df = pd.read_csv("signnames.csv")
return
def signName(self, class_id):
return self.df.at[class_id, 'SignName']
signnames_csv = SignNames_CSV()
def signName(class_id):
'''
Returns name of sign given class_id.
Params:
- class_id: integer from 0-42 representing id number of sign name
Notes:
- Example: signName(0) retturns "Speed limit (20km/h)".
- Use to map dataset label to sign name
'''
return signnames_csv.signName(class_id)
class TrafficSignsDataset:
'''
Wrapper for the training, validation, and testing datasets.
'''
def __init__(self, *args):
self.logger = Logger("TrafficSignsDataset", self)
if len(args) == 3:
# initialized with imags, labels and n_classes
images, labels, n_classes = args
else:
# len args == 2
# initializes with folder_name and n_classes
folder_name, n_classes = args
images, labels = self.loadFolder(folder_name)
self.org_X = images
self.org_y = labels
self.X = self.org_X.copy()
self.y = self.org_y.copy()
self.n_classes = n_classes
return
def loadFolder(self, folder_name):
msg = "Loading signs from {}..."
self.logger.log(msg.format(folder_name))
pathnames = [join(folder_name, f)
for f in listdir(folder_name) if isfile(join(folder_name, f))]
n = 0
images = []
labels = []
for pathname in pathnames:
filename = basename(pathname)
classId = filename.split(",")[0]
pil_img = Image.open(pathname).convert('RGB')
pil_img20x20 = pil_img.resize((20, 20), Image.BILINEAR)
img = np.pad (np.array(pil_img20x20), [(6, 6), (6, 6), (0, 0)])
'''
#if not padding, use:
pil_img32x32 = pil_img.resize((32, 32), Image.BILINEAR)
img = np.array(pil_img32x32)
'''
labels.append(classId)
images.append(img)
msg = "Loaded {} with label {}."
self.logger.log(msg.format(filename, classId))
n += 1
msg = "...{} signs loaded."
self.logger.log (msg.format(n))
return images, labels
def data(self):
return (self.X, self.y)
def processImages(self, img_processors):
self.logger.log("Processing images...")
for img_processor in img_processors:
msg = "Applying {}() to images."
self.logger.log(msg.format(img_processor.__name__))
self.X = [img_processor(img) for img in self.X]
self.logger.log("...images processed.")
return
def addFakes (self, img_processors):
self.logger.log("Adding fake images...")
max_samples = np.max(np.bincount(self.y)) * 3
total_added = 0
for classId in range(self.n_classes):
x = self.X[self.y == classId]
y = self.y[self.y == classId]
n_x = x.shape[0]
aug_x = np.array([])
aug_y = np.array([])
if n_x < max_samples:
n_repeats = (max_samples - n_x) // n_x
n_remain = (max_samples - n_x) % n_x
aug_x = np.repeat(x, n_repeats, axis=0)
aug_x = np.concatenate ((aug_x, x[:n_remain]))
for img_processor in img_processors:
aug_x = np.array([img_processor(img) for img in aug_x])
aug_y = np.repeat(y, n_repeats, axis=0)
aug_y = np.concatenate ((aug_y, y[:n_remain]))
samples_added = max_samples - n_x
msg = "Added {} fake images for classId {}."
self.logger.log(msg.format(samples_added, classId))
total_added += samples_added
if aug_x.shape[0] > 0:
self.X = np.concatenate((self.X, aug_x))
self.y = np.concatenate((self.y, aug_y))
self.X = np.array(self.X, dtype=np.uint8)
msg = "...{:,} fake images added."
self.logger.log (msg.format(total_added))
msg= "{:,} samples available for training."
self.logger.log (msg.format(self.X.shape[0]))
return
def restoreOrgImages(self):
self.X = np.array(self.org_X, dtype=np.uint8)
self.y = np.array(self.org_y)
self.logger.log("Original images and labels restored.")
return
class Viewer:
'''
Provides methods for plotting data on notebook.
'''
def __init__(self):
return
def imShowTrainingSigns(self, trainingSigns):
ds = list(zip(trainingSigns.y, trainingSigns.X))
df = pd.DataFrame(data=ds, columns=['Label', 'Image'])
n_samples = 6
for classId in range(trainingSigns.n_classes):
# https://pandas.pydata.org/pandas-docs/version/0.15/cookbook.html#building-criteria
df_sel = df.loc[(df['Label'] == classId), 'Image'].sample(n_samples)
fig, axes = plt.subplots(1, n_samples, figsize=(11, 1.25))
plt.axis('off')
fig.suptitle(signName(classId), y=1.12)
for i in range(n_samples):
axes[i].xaxis.set_visible(False)
axes[i].yaxis.set_visible(False)
axes[i].imshow(df_sel.iloc[i])
plt.show()
return
def imShowTrainingSigns5x5(self, trainingSigns):
fig = plt.figure(figsize=(11,11))
num_rows = 5
num_cols = 5
for i in range(num_cols*num_rows):
img = random.choice(trainingSigns.X)
ax = plt.subplot(num_rows, num_cols, i + 1)
ax.imshow(img)
plt.show()
return
def imShowImages(self, images, titles=None):
n_images = len(images)
n_cols = 5
n_rows = n_images//n_cols + 1
plt.figure(figsize=(11, (2.5 * n_rows)))
for i, img in enumerate(images):
ax = plt.subplot(n_rows, n_cols, i + 1)
ax.imshow(img)
if titles is not None:
ax.set_title(titles[i])
return
def barhPctBySigns(self, trainingSigns, validSigns, testSigns):
y_train = trainingSigns.y
y_valid = validSigns.y
y_test = testSigns.y
bincount_y_train = np.bincount(y_train)
bincount_y_valid = np.bincount(y_valid)
bincount_y_test = np.bincount(y_test)
# bin_count[i] = num samples for sign i (where i=classId)
pct_y_train = bincount_y_train / sum(bincount_y_train)
pct_y_valid = bincount_y_valid / sum(bincount_y_valid)
pct_y_test = bincount_y_test / sum(bincount_y_test)
# pct_y_train[i] = percentage of total samples of sign i
pct_y_train_sorted_idx = np.argsort(pct_y_train)
# pct_y_train_sorted_idx an array of sign classIds sorted by their percentage
# ref: https://stackoverflow.com/a/59421062
bar_wid = 0.3
y_pos = np.arange(len(pct_y_train))
pcts = [pct_y_train[class_id] for class_id in pct_y_train_sorted_idx]
pcts_valid = [pct_y_valid[class_id] for class_id in pct_y_train_sorted_idx]
pcts_test = [pct_y_test[class_id] for class_id in pct_y_train_sorted_idx]
y_labels = [textwrap.fill(signName(class_id), width=25)
for class_id in pct_y_train_sorted_idx]
fig, ax = plt.subplots(figsize=(11, 35))
ax.barh(y_pos + 2*bar_wid, pcts, bar_wid, label="Training")
ax.barh(y_pos + bar_wid, pcts_valid, bar_wid, label="Valid")
ax.barh(y_pos, pcts_test, bar_wid, label="Test")
ax.set_yticks(y_pos + bar_wid)
ax.set_yticklabels(y_labels)
ax.set_xlabel('Percentage of Sample')
ax.set_title("Percentage of Sample by Sign and Dataset")
plt.legend(loc='best')
plt.margins(y=0)
plt.show()
return
def barhCountTrainingSigns(self, trainingSigns):
sign_count_y_train = np.bincount(trainingSigns.y)
# ref: https://stackoverflow.com/a/59421062
y_pos = np.arange(len(sign_count_y_train))
counts_train = [sign_count_y_train[class_id]
for class_id in range(trainingSigns.n_classes)]
y_labels = [textwrap.fill(signName(class_id), width=25)
for class_id in range(trainingSigns.n_classes)]
fig, ax = plt.subplots(figsize=(11, 35))
# ax.barh(y_pos, counts_train)
ax.barh(y_pos, counts_train)
ax.set_yticks(y_pos)
ax.set_yticklabels(y_labels)
ax.invert_yaxis()
ax.set_xlabel('Number of Training Samples')
ax.set_title("Number of Training Samples by Sign")
plt.margins(y=0)
plt.show()
return
def imShowPredictions(self, model_name, images, predictions):
num_images = len(images)
fig, axs = plt.subplots(num_images, 2, figsize=(15, 3.5*num_images))
if num_images == 1:
axs = [axs]
for ax, img, vals, idxs in zip(axs, images, predictions.values, predictions.indices):
pcts = [100*v for v in vals]
signs = [textwrap.fill(signName(i), width=25) for i in idxs]
# https://matplotlib.org/gallery/lines_bars_and_markers/barh.html#sphx-glr-gallery-lines-bars-and-markers-barh-py
img_ax = ax[0]
bar_ax = ax[1]
img_ax.imshow(img)
img_ax.set_title("Image of Sign")
ypos = np.arange(len(signs))
bar_ax.barh(ypos, pcts)
bar_ax.set_yticks(ypos)
bar_ax.set_yticklabels(signs)
bar_ax.invert_yaxis()
bar_ax.set_xlabel("Confidence")
bar_ax.set_title("Classification (Top 5)")
bar_ax.set_xlim([0,100])
fig.suptitle(model_name + " Classification of some German Traffic Signs", y = 1.0)
fig.tight_layout()
plt.show()
return
def imShowConvOutputs(self, conv_outputs):
# layer_ouputs in shape (1, ?, ?, depth)
features = layer_outputs[0]
depth = layer_outputs.shape[3]
plt.figure(figsize=(15, (2.5 * (depth//8 + 1))))
n_cols = 8
n_rows = depth//n_cols + 1
for level in range(depth):
img = features[:,:,level] * 255
plt.subplot(n_rows, n_cols, level + 1)
plt.imshow(img,
interpolation='nearest',
cmap='gray',
vmin=np.amin(img), vmax=np.amax(img))
return
def plotAccHist(self, model_name, acc_hist):
epoch = [e for e in range(len(acc_hist))]
plt.plot(epoch, acc_hist)
plt.title("Accuracy over Epoch for " + model_name)
plt.xlabel("Epoch")
plt.ylabel("Accuracy")
plt.show()
return
trainingSigns = TrafficSignsDataset(X_train, y_train, n_classes)
validSigns = TrafficSignsDataset(X_valid, y_valid, n_classes)
testSigns = TrafficSignsDataset(X_test, y_test, n_classes)
vwr = Viewer()
View signs in trainingSigns dataset sorted by type.
vwr.imShowTrainingSigns(trainingSigns)
vwr.barhPctBySigns(trainingSigns, validSigns, testSigns)
Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.
The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!
With the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission.
There are various aspects to consider when thinking about this problem:
Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.
Minimally, the image data should be normalized so that the data has mean zero and equal variance. For image data, (pixel - 128)/ 128 is a quick way to approximately normalize the data and can be used in this project.
Other pre-processing steps are optional. You can try different techniques to see if it improves performance.
Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.
### Preprocess the data here. It is required to normalize the data. Other preprocessing steps could include
### converting to grayscale, etc.
### Feel free to use as many code cells as needed.
import numpy as np
import cv2
import skimage as sk
from skimage.transform import rotate
equalizeHist() will brighten dark imagesimage_processors is a list of the pre-processor functions applied to datasets before use in training and testing model.shift(), zoom(), etc used in generating additional training samples.def RGB_to_norm(img):
return (np.float32(img) - 128)/128
def norm_to_RGB(norm_img):
return (np.uint8(128 * norm_img) + 128)
def equalizeHist(orgimg, v_thresh=128):
'''
Brightens dark images.
Params:
- orgimg: original image (RGB)
- v_thresh: max integer of the average value of the image for brightening to occur
'''
hsv = cv2.cvtColor(orgimg, cv2.COLOR_RGB2HSV)
mean_v = np.mean(hsv[:,:,2])
if mean_v < v_thresh:
equ = cv2.equalizeHist(hsv[:,:,2])
hsv[:,:,2] = equ
img = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)
else:
img = orgimg
return img
image_processors = [equalizeHist, RGB_to_norm]
# https://medium.com/@thimblot/data-augmentation-boost-your-image-dataset-with-few-lines-of-python-155c2dc1baec
def shift(image, d=None):
'''
Shifts image left, right, up or down from 1 to 6 pixels.
Used in generating additional training samples.
'''
if d is None:
d = random.randint(1, 6)
direction = random.choice([1, 2, 3, 4])
if direction == 1:
image[:-d] = image[d:]
elif direction == 2:
image[d:] = image[:-d]
elif direction == 3:
image[:,d:] = image[:,:-d]
else:
image[:,:-d] = image[:,d:]
return image
def crop(image, size=32):
'''
Crops image to 32x32. Used after image is zoomed in.
'''
sizes = np.array(image.shape[:2]) - 32
lower = sizes // 2
upper = image.shape[:2] - (lower + (sizes % 2))
img = image[lower[0]:upper[0], lower[1]:upper[1]]
return img
def zoom(image, scale=None):
'''
Zooms in on an image from 1.0x to 1.6x. Uses crop to ensure img is 32x32
Used in generating additional training samples.
'''
if scale is None:
scale = random.uniform(1.0, 1.6)
img = sk.transform.rescale(image, scale, multichannel=True, preserve_range=True).astype(np.uint8)
return crop(img)
def rotate (image, deg=None):
'''
Rotates image from -15 to 15 degrees.
Used in generating additional training samples.
'''
if deg is None:
deg = random.uniform(-15, 15)
return sk.transform.rotate(image, deg, preserve_range=True).astype(np.uint8)
def preserve(image):
'''
Use same image.
Used in generating additional training samples.
'''
return image.astype(np.uint8)
def fakeify(image):
'''
Generates fake images to increase number of training samples.
Notes:
- Randomly selects from preserve, rotate, zoom, shift to generate image.
'''
f = random.choices ([preserve, rotate, zoom, shift], weights=[1, 3, 3, 3])[0]
return f(image)
trainingSigns.restoreOrgImages()
org_image = trainingSigns.X[1000].copy()
brt_image = equalizeHist(org_image.copy())
rot_image = rotate(brt_image.copy(), 15)
zm_image = zoom(brt_image.copy(), 1.6)
shf_image = shift(brt_image.copy(), 6)
images = [org_image, brt_image, rot_image, zm_image, shf_image]
titles = ["Original", "Brightened", "Rotated", "Zoomed", "Shifted"]
vwr.imShowImages(images, titles)
TrafficSignsDataset-2112 | Original images and labels restored.
A total of 259,290 samples are used for training after adding additional training samples.
trainingSigns.restoreOrgImages()
trainingSigns.addFakes([fakeify])
TrafficSignsDataset-2112 | Original images and labels restored. TrafficSignsDataset-2112 | Adding fake images... TrafficSignsDataset-2112 | Added 5850 fake images for classId 0. TrafficSignsDataset-2112 | Added 4050 fake images for classId 1. TrafficSignsDataset-2112 | Added 4020 fake images for classId 2. TrafficSignsDataset-2112 | Added 4770 fake images for classId 3. TrafficSignsDataset-2112 | Added 4260 fake images for classId 4. TrafficSignsDataset-2112 | Added 4380 fake images for classId 5. TrafficSignsDataset-2112 | Added 5670 fake images for classId 6. TrafficSignsDataset-2112 | Added 4740 fake images for classId 7. TrafficSignsDataset-2112 | Added 4770 fake images for classId 8. TrafficSignsDataset-2112 | Added 4710 fake images for classId 9. TrafficSignsDataset-2112 | Added 4230 fake images for classId 10. TrafficSignsDataset-2112 | Added 4860 fake images for classId 11. TrafficSignsDataset-2112 | Added 4140 fake images for classId 12. TrafficSignsDataset-2112 | Added 4110 fake images for classId 13. TrafficSignsDataset-2112 | Added 5340 fake images for classId 14. TrafficSignsDataset-2112 | Added 5490 fake images for classId 15. TrafficSignsDataset-2112 | Added 5670 fake images for classId 16. TrafficSignsDataset-2112 | Added 5040 fake images for classId 17. TrafficSignsDataset-2112 | Added 4950 fake images for classId 18. TrafficSignsDataset-2112 | Added 5850 fake images for classId 19. TrafficSignsDataset-2112 | Added 5730 fake images for classId 20. TrafficSignsDataset-2112 | Added 5760 fake images for classId 21. TrafficSignsDataset-2112 | Added 5700 fake images for classId 22. TrafficSignsDataset-2112 | Added 5580 fake images for classId 23. TrafficSignsDataset-2112 | Added 5790 fake images for classId 24. TrafficSignsDataset-2112 | Added 4680 fake images for classId 25. TrafficSignsDataset-2112 | Added 5490 fake images for classId 26. TrafficSignsDataset-2112 | Added 5820 fake images for classId 27. TrafficSignsDataset-2112 | Added 5550 fake images for classId 28. TrafficSignsDataset-2112 | Added 5790 fake images for classId 29. TrafficSignsDataset-2112 | Added 5640 fake images for classId 30. TrafficSignsDataset-2112 | Added 5340 fake images for classId 31. TrafficSignsDataset-2112 | Added 5820 fake images for classId 32. TrafficSignsDataset-2112 | Added 5431 fake images for classId 33. TrafficSignsDataset-2112 | Added 5670 fake images for classId 34. TrafficSignsDataset-2112 | Added 4950 fake images for classId 35. TrafficSignsDataset-2112 | Added 5700 fake images for classId 36. TrafficSignsDataset-2112 | Added 5850 fake images for classId 37. TrafficSignsDataset-2112 | Added 4170 fake images for classId 38. TrafficSignsDataset-2112 | Added 5760 fake images for classId 39. TrafficSignsDataset-2112 | Added 5730 fake images for classId 40. TrafficSignsDataset-2112 | Added 5820 fake images for classId 41. TrafficSignsDataset-2112 | Added 5820 fake images for classId 42. TrafficSignsDataset-2112 | ...224,491 fake images added. TrafficSignsDataset-2112 | 259,290 samples available for training.
vwr.imShowTrainingSigns5x5(trainingSigns)
After generating additional samples for training, the number of samples for each sign should be equal.
vwr.barhCountTrainingSigns(trainingSigns)
Brighten and normalize datasets.
trainingSigns.processImages(image_processors)
validSigns.restoreOrgImages()
validSigns.processImages(image_processors)
testSigns.restoreOrgImages()
testSigns.processImages(image_processors)
TrafficSignsDataset-2112 | Processing images... TrafficSignsDataset-2112 | Applying equalizeHist() to images. TrafficSignsDataset-2112 | Applying RGB_to_norm() to images. TrafficSignsDataset-2112 | ...images processed. TrafficSignsDataset-2784 | Original images and labels restored. TrafficSignsDataset-2784 | Processing images... TrafficSignsDataset-2784 | Applying equalizeHist() to images. TrafficSignsDataset-2784 | Applying RGB_to_norm() to images. TrafficSignsDataset-2784 | ...images processed. TrafficSignsDataset-3008 | Original images and labels restored. TrafficSignsDataset-3008 | Processing images... TrafficSignsDataset-3008 | Applying equalizeHist() to images. TrafficSignsDataset-3008 | Applying RGB_to_norm() to images. TrafficSignsDataset-3008 | ...images processed.
### Define your architecture here.
### Feel free to use as many code cells as needed.
import tensorflow as tf
from tensorflow.contrib.layers import flatten
from sklearn.utils import shuffle
from PIL import Image
WARNING: Logging before flag parsing goes to stderr. W0207 17:37:22.460557 14992 __init__.py:329] Limited tf.compat.v2.summary API due to missing TensorBoard installation.
Functions below help to create convolutional, pooling and fully connected layers.
def conv2D(x, output_shape, s=1, mu=0, sigma=0.1, activation=tf.nn.relu):
input_shape = x.shape.as_list()[1:]
input_depth = input_shape[2]
output_depth = output_shape[2]
stride = [1, s, s, 1]
# size of filter (length=Width)
# ref: lesson 12: Solution: Convolution Output Shape for "VALID" padding
f_ht = input_shape[0] - output_shape[0]*s + 1
f_wid = input_shape[1] - output_shape[1]*s + 1
# shape of weights
w_shape = (f_ht, f_wid, input_depth, output_depth)
w = tf.Variable(tf.truncated_normal(w_shape, mu, sigma))
b = tf.Variable(tf.zeros(output_depth))
c = tf.nn.conv2d(x, w, stride, padding='VALID') + b
a = activation(c)
return a
def pooling(x, output_shape, s=2, pool=tf.nn.max_pool):
input_shape = x.shape.as_list()[1:]
input_depth = input_shape[2]
# size of filter
# ref: lesson 23: Quiz: Pooling Mechanics
f_ht = input_shape[0] - (output_shape[0] - 1) * s
f_wid = input_shape[1] - (output_shape[1] - 1) * s
fil = [1, f_ht, f_wid, 1]
stride = [1, s, s, 1]
p = pool(x, fil, stride, padding='VALID')
return p
def connected(x, output_shape, mu=0, sigma=0.1, activation=tf.nn.relu):
input_shape = x.shape.as_list()[1]
output_shape = output_shape[0]
w_shape = (input_shape, output_shape)
w = tf.Variable(tf.truncated_normal(w_shape, mu, sigma))
b = tf.Variable(tf.zeros(output_shape))
z = tf.add(tf.matmul(x, w), b)
if activation is None:
a = z
else:
a = activation(z)
return a
Classes below wrap the helper functions above. A Keras-inspired convention is used in creating layers and models.
class Layer():
def __init__(self, output_shape=None):
self.output_shape = output_shape
self.tensor = None
self.model = None
self.setName()
return
def setName(self):
self.name = "Layer"
return
def summary(self):
return self.name.ljust(10) + ":" + str(self.tensor.shape)
def connect(self, *prev_layers):
self.tensor = prev_layers[0].tensor
return self
def owner(self, model = None):
if model is not None:
self.model = model
return self.model
class Input(Layer):
def __init__(self, X):
super().__init__(self)
self.tensor = X
def setName(self):
self.name = "Input"
return
class Conv2D(Layer):
def setName(self):
self.name = "Conv2D"
return
def connect(self, *prev_layer):
self.model = prev_layer[0].model
self.tensor = conv2D(prev_layer[0].tensor, self.output_shape)
return self
class Pooling(Layer):
def setName(self):
self.name = "Pooling"
return
def connect(self, *prev_layer):
self.model = prev_layer[0].model
self.tensor = pooling(prev_layer[0].tensor, self.output_shape)
return self
class Dropout(Layer):
def setName(self):
self.name = "Dropout"
return
def connect(self, *prev_layer):
self.model = prev_layer[0].model
self.keep_prob = self.model.keep_prob
self.tensor = tf.nn.dropout(prev_layer[0].tensor, self.keep_prob)
return self
class Flatten(Layer):
def setName(self):
self.name = "Flatten"
return
def connect(self, *prev_layer):
self.model = prev_layer[0].model
self.tensor = flatten(prev_layer[0].tensor)
return self
class Connected(Layer):
def setName(self):
self.name = "Connected"
return
def connect(self, *prev_layer):
self.model = prev_layer[0].model
self.tensor = connected(prev_layer[0].tensor, self.output_shape)
return self
A base Model class and Sequential Model Keras-inspired classed are defined below. The base Model class is used to construct a multi-scale network then Optional section of this project. The more traditional Sequential is used to construct the main classifier for this project.
class Model:
def __init__(self, name, input_shape, n_classes):
self.logger = Logger('Model', self)
self.name = name
x_shape = (None, input_shape[0], input_shape[1], input_shape[2])
self.x = tf.placeholder(tf.float32, x_shape)
self.input_layer = Input(self.x)
self.input_layer.owner(self)
self.y = tf.placeholder(tf.int32, (None))
self.keep_prob = tf.placeholder(tf.float32)
self.n_classes = n_classes
self.logits = None
self.saver = None
self.acc_history = None
return
def inputLayer(self):
return self.input_layer
def connectLogits(self, prev_layer):
self.logits = connected(prev_layer.tensor, [self.n_classes], activation=None)
oh_labels = tf.one_hot(self.y, self.n_classes)
losses = tf.nn.softmax_cross_entropy_with_logits(labels=oh_labels, logits=self.logits)
self.mean_loss = tf.reduce_mean(losses)
correct_prediction = tf.equal(tf.argmax(self.logits, 1), tf.argmax(oh_labels, 1))
self.tot_correct = tf.reduce_sum(tf.cast(correct_prediction, tf.float32))
def accuracy(self, X_data, y_data, batch_size):
num_examples = len(X_data)
total_correct = 0
sess = tf.get_default_session()
for offset in range(0, num_examples, batch_size):
batch_x = X_data[offset:offset+batch_size]
batch_y = y_data[offset:offset+batch_size]
feed_dict = {self.x: batch_x,
self.y: batch_y,
self.keep_prob: 1.0}
batch_correct = sess.run(self.tot_correct, feed_dict=feed_dict)
total_correct += batch_correct
return round (total_correct / num_examples, 3)
def saveModel(self):
sess = tf.get_default_session()
self.saver.save(sess, "checkpoints/" + self.name)
msg = "{} saved."
self.logger.log(msg.format(self.name))
return
def afterEpoch(self, epoch, i, acc, acc_save, hi_acc):
self.acc_history.append(acc)
i += 1
if acc > acc_save:
if acc > hi_acc:
i = 0
hi_acc = acc
msg = "Epoch {:4d} - New High Acc: {:.3f}"
self.logger.log(msg.format(epoch + 1, hi_acc))
self.saveModel()
else:
msg = "Epoch {:4d} - Acc: {:.3f} - Highest: {:.3f}"
self.logger.log(msg.format(epoch + 1, acc, hi_acc))
elif hi_acc > 0:
msg = "Epoch {:4d} - Acc: {:.3f} - Highest: {:.3f}"
self.logger.log(msg.format(epoch + 1, acc, hi_acc))
else:
msg = "Epoch {:4d} - Acc: {:.3f}"
self.logger.log(msg.format(epoch + 1, acc))
epoch += 1
return epoch, i, hi_acc
def train(self, training_data, validation_data, epochs_done, batch_size, lr=0.001,
acc_save=0.93, acc_done=0.982, keep_prob=1.0, ):
X_train = training_data[0]
y_train = training_data[1]
X_valid = validation_data[0]
y_valid = validation_data[1]
optimizer = tf.train.AdamOptimizer(learning_rate=lr)
minimizer = optimizer.minimize(self.mean_loss)
self.saver = tf.train.Saver()
self.logger.log("Training...")
with tf.Session() as sess:
try:
sess.run(tf.global_variables_initializer())
num_examples = len(X_train)
self.acc_history = []
hi_acc = 0
epoch = 0
i = 0
acc = 0
while (i < epochs_done) and (acc < acc_done):
X_train, y_train = shuffle(X_train, y_train)
for offset in range(0, num_examples, batch_size):
end = offset + batch_size
batch_x = X_train[offset:end]
batch_y = y_train[offset:end]
feed_dict = {self.x : batch_x,
self.y : batch_y,
self.keep_prob: keep_prob}
sess.run(minimizer, feed_dict=feed_dict)
acc = self.accuracy(X_valid, y_valid, batch_size)
epoch, i, hi_acc = self.afterEpoch(epoch, i, acc, acc_save, hi_acc)
# https://stackoverflow.com/a/45033800
except KeyboardInterrupt:
self.logger.log("Manually terminated.")
msg = "...training complete. Highest accuracy: {:.3f}."
self.logger.log(msg.format(hi_acc))
return
def accHist(self):
return self.acc_history
def test(self, test_data):
X_test = test_data[0]
y_test = test_data[1]
with tf.Session() as sess:
self.restore()
test_acc = self.accuracy(X_test, y_test, batch_size=128)
msg = "Test accuracy: {:.3f}."
self.logger.log(msg.format(test_acc))
return
def predict(self, images, top=5):
with tf.Session() as sess:
self.restore()
predictions = []
self.logger.log("Classifying images...")
op_top_k = tf.nn.top_k(tf.nn.softmax(self.logits), top)
feed_dict = {self.x : images,
self.keep_prob: 1.0}
predictions = sess.run(op_top_k, feed_dict=feed_dict)
msg = "...{} images classified."
self.logger.log(msg.format(len(images)))
return predictions
def restore(self):
saver = tf.train.Saver()
sess = tf.get_default_session()
saver.restore(sess, "checkpoints/" + self.name)
msg = "{} restored."
self.logger.log(msg.format(self.name))
return
class Sequential(Model):
def __init__(self, name, input_shape, n_classes):
super().__init__(name, input_shape, n_classes)
self.layers = []
return
def addLayer(self, layer):
self.layers.append(layer)
return
def assemble(self):
prev_layer = self.input_layer
for layer in self.layers:
prev_layer = layer.connect(prev_layer)
self.connectLogits(prev_layer)
msg = "{} assembled."
self.logger.log(msg.format(self.name))
return
def summarize(self):
msg = " Summary for {}:"
self.logger.log(msg.format(self.name))
self.logger.log("----------------------------------")
msg = " Input".ljust(15) + ":{}"
self.logger.log(msg.format(self.x.shape))
self.logger.log("----------------------------------")
n = 0
for layer in self.layers:
msg = "{:<2} : " + layer.summary()
self.logger.log(msg.format(n))
n += 1
self.logger.log("----------------------------------")
msg = " Logits".ljust(15) + ":{}"
self.logger.log(msg.format(self.logits.shape))
self.logger.log("----------------------------------")
return
def eval_layer(self, i, img):
msg = "Evaluating layer {}."
self.logger.log(msg.format(i))
tensor = self.layers[i].tensor
feed_dict = {self.x : [img],
self.keep_prob: 1.0}
with tf.Session() as sess:
self.restore()
eval_outputs = tensor.eval(session=sess, feed_dict=feed_dict)
msg = "Output shape: {}."
self.logger.log(msg.format(eval_outputs.shape))
return eval_outputs
The Sequential model is used to add the layers to develop the classifiers. Layers are added "sequentially" to the model.
The model architecture generally follows the LeNet architecture outlined in Lesson 13: Convolutional Neural Networks, Item 36. Lab: LeNet in Tensorflow.
A 1x1 convolution used in the very first layer has an output shape of 32x32x1. During development, this allowed the sequential model to improve validation accuracy as compared to training the model without it.
The other convolutional layers have the same first and second dimensions as the LeNet, but are deeper. The fully connected layers are wider with dropout added in the later stages.
notLenet = Sequential("notLeNet", input_shape=image_shape, n_classes=n_classes)
notLenet.addLayer (Conv2D ([32, 32, 1]))
notLenet.addLayer (Conv2D ([28, 28, 24]))
notLenet.addLayer (Pooling ([14, 14]))
notLenet.addLayer (Conv2D ([10, 10, 64]))
notLenet.addLayer (Pooling ([5, 5]))
notLenet.addLayer (Flatten ())
notLenet.addLayer (Connected([240]))
notLenet.addLayer (Dropout ())
notLenet.addLayer (Connected([168]))
notLenet.addLayer (Dropout ())
notLenet.assemble()
W0207 17:38:01.617027 14992 deprecation.py:323] From C:\Users\Owner\anaconda3\envs\tsc\lib\site-packages\tensorflow_core\contrib\layers\python\layers\layers.py:1634: flatten (from tensorflow.python.layers.core) is deprecated and will be removed in a future version. Instructions for updating: Use keras.layers.flatten instead. W0207 17:38:01.619022 14992 deprecation.py:323] From C:\Users\Owner\anaconda3\envs\tsc\lib\site-packages\tensorflow_core\python\layers\core.py:332: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version. Instructions for updating: Please use `layer.__call__` method instead. W0207 17:38:01.633983 14992 deprecation.py:506] From <ipython-input-17-4632de4b3f83>:71: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version. Instructions for updating: Please use `rate` instead of `keep_prob`. Rate should be set to `rate = 1 - keep_prob`. W0207 17:38:01.661935 14992 deprecation.py:323] From <ipython-input-18-1c9f36fa1026>:32: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version. Instructions for updating: Future major versions of TensorFlow will allow gradients to flow into the labels input on backprop by default. See `tf.nn.softmax_cross_entropy_with_logits_v2`.
Model-6472 | notLeNet assembled.
Layers and respective output shapes are printed to verify architecture.
notLenet.summarize()
Model-6472 | Summary for notLeNet: Model-6472 | ---------------------------------- Model-6472 | Input :(?, 32, 32, 3) Model-6472 | ---------------------------------- Model-6472 | 0 : Conv2D :(?, 32, 32, 1) Model-6472 | 1 : Conv2D :(?, 28, 28, 24) Model-6472 | 2 : Pooling :(?, 14, 14, 24) Model-6472 | 3 : Conv2D :(?, 10, 10, 64) Model-6472 | 4 : Pooling :(?, 5, 5, 64) Model-6472 | 5 : Flatten :(?, 1600) Model-6472 | 6 : Connected :(?, 240) Model-6472 | 7 : Dropout :(?, 240) Model-6472 | 8 : Connected :(?, 168) Model-6472 | 9 : Dropout :(?, 168) Model-6472 | ---------------------------------- Model-6472 | Logits :(?, 43) Model-6472 | ----------------------------------
A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.
### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected,
### the accuracy on the test set should be calculated and reported as well.
### Feel free to use as many code cells as needed.
'''
Batch size of batch_size=128 was chosen through trial and error.
Training terminates once epochs_done=64 epochs have passed
since last highest validation accuracy was detected.
If validation accuracy reaches acc_done=0.997, training will also terminate.
Model is saved every time a new high accuracy is achieved.
Keep probability for the dropout layers is keep_prob=0.5.
'''
notLenet.train(trainingSigns.data(), validSigns.data(), batch_size=128,
epochs_done=64, acc_done=0.997, keep_prob=0.5)
Model-6472 | Training... Model-6472 | Epoch 1 - Acc: 0.924 Model-6472 | Epoch 2 - New High Acc: 0.961 Model-6472 | notLeNet saved. Model-6472 | Epoch 3 - New High Acc: 0.967 Model-6472 | notLeNet saved. Model-6472 | Epoch 4 - New High Acc: 0.971 Model-6472 | notLeNet saved. Model-6472 | Epoch 5 - New High Acc: 0.979 Model-6472 | notLeNet saved. Model-6472 | Epoch 6 - Acc: 0.975 - Highest: 0.979 Model-6472 | Epoch 7 - Acc: 0.975 - Highest: 0.979 Model-6472 | Epoch 8 - New High Acc: 0.981 Model-6472 | notLeNet saved. Model-6472 | Epoch 9 - Acc: 0.972 - Highest: 0.981 Model-6472 | Epoch 10 - Acc: 0.981 - Highest: 0.981 Model-6472 | Epoch 11 - Acc: 0.980 - Highest: 0.981 Model-6472 | Epoch 12 - Acc: 0.975 - Highest: 0.981 Model-6472 | Epoch 13 - Acc: 0.977 - Highest: 0.981 Model-6472 | Epoch 14 - Acc: 0.981 - Highest: 0.981 Model-6472 | Epoch 15 - Acc: 0.981 - Highest: 0.981 Model-6472 | Epoch 16 - Acc: 0.973 - Highest: 0.981 Model-6472 | Epoch 17 - Acc: 0.978 - Highest: 0.981 Model-6472 | Epoch 18 - New High Acc: 0.982 Model-6472 | notLeNet saved. Model-6472 | Epoch 19 - New High Acc: 0.983 Model-6472 | notLeNet saved. Model-6472 | Epoch 20 - New High Acc: 0.984 Model-6472 | notLeNet saved. Model-6472 | Epoch 21 - Acc: 0.982 - Highest: 0.984 Model-6472 | Epoch 22 - Acc: 0.983 - Highest: 0.984 Model-6472 | Epoch 23 - Acc: 0.977 - Highest: 0.984 Model-6472 | Epoch 24 - New High Acc: 0.988 Model-6472 | notLeNet saved. Model-6472 | Epoch 25 - Acc: 0.984 - Highest: 0.988 Model-6472 | Epoch 26 - Acc: 0.974 - Highest: 0.988 Model-6472 | Epoch 27 - Acc: 0.979 - Highest: 0.988 Model-6472 | Epoch 28 - Acc: 0.982 - Highest: 0.988 Model-6472 | Epoch 29 - Acc: 0.980 - Highest: 0.988 Model-6472 | Epoch 30 - Acc: 0.984 - Highest: 0.988 Model-6472 | Epoch 31 - Acc: 0.978 - Highest: 0.988 Model-6472 | Epoch 32 - Acc: 0.981 - Highest: 0.988 Model-6472 | Epoch 33 - Acc: 0.985 - Highest: 0.988 Model-6472 | Epoch 34 - Acc: 0.985 - Highest: 0.988 Model-6472 | Epoch 35 - Acc: 0.983 - Highest: 0.988 Model-6472 | Epoch 36 - Acc: 0.981 - Highest: 0.988 Model-6472 | Epoch 37 - Acc: 0.983 - Highest: 0.988 Model-6472 | Epoch 38 - Acc: 0.985 - Highest: 0.988 Model-6472 | Epoch 39 - Acc: 0.985 - Highest: 0.988 Model-6472 | Epoch 40 - Acc: 0.980 - Highest: 0.988 Model-6472 | Epoch 41 - Acc: 0.983 - Highest: 0.988 Model-6472 | Epoch 42 - Acc: 0.984 - Highest: 0.988 Model-6472 | Epoch 43 - Acc: 0.981 - Highest: 0.988 Model-6472 | Epoch 44 - Acc: 0.981 - Highest: 0.988 Model-6472 | Epoch 45 - Acc: 0.983 - Highest: 0.988 Model-6472 | Epoch 46 - Acc: 0.987 - Highest: 0.988 Model-6472 | Epoch 47 - Acc: 0.984 - Highest: 0.988 Model-6472 | Epoch 48 - Acc: 0.984 - Highest: 0.988 Model-6472 | Epoch 49 - Acc: 0.985 - Highest: 0.988 Model-6472 | Epoch 50 - Acc: 0.985 - Highest: 0.988 Model-6472 | Epoch 51 - Acc: 0.980 - Highest: 0.988 Model-6472 | Epoch 52 - Acc: 0.981 - Highest: 0.988 Model-6472 | Epoch 53 - Acc: 0.981 - Highest: 0.988 Model-6472 | Epoch 54 - Acc: 0.984 - Highest: 0.988 Model-6472 | Epoch 55 - Acc: 0.985 - Highest: 0.988 Model-6472 | Epoch 56 - Acc: 0.985 - Highest: 0.988 Model-6472 | Epoch 57 - Acc: 0.987 - Highest: 0.988 Model-6472 | Epoch 58 - Acc: 0.980 - Highest: 0.988 Model-6472 | Epoch 59 - Acc: 0.981 - Highest: 0.988 Model-6472 | Epoch 60 - Acc: 0.980 - Highest: 0.988 Model-6472 | Epoch 61 - Acc: 0.983 - Highest: 0.988 Model-6472 | Epoch 62 - Acc: 0.983 - Highest: 0.988 Model-6472 | Epoch 63 - Acc: 0.982 - Highest: 0.988 Model-6472 | Epoch 64 - Acc: 0.983 - Highest: 0.988 Model-6472 | Epoch 65 - Acc: 0.972 - Highest: 0.988 Model-6472 | Epoch 66 - Acc: 0.983 - Highest: 0.988 Model-6472 | Epoch 67 - Acc: 0.982 - Highest: 0.988 Model-6472 | Epoch 68 - Acc: 0.981 - Highest: 0.988 Model-6472 | Epoch 69 - Acc: 0.986 - Highest: 0.988 Model-6472 | Epoch 70 - Acc: 0.984 - Highest: 0.988 Model-6472 | Epoch 71 - Acc: 0.983 - Highest: 0.988 Model-6472 | Epoch 72 - Acc: 0.986 - Highest: 0.988 Model-6472 | Epoch 73 - Acc: 0.979 - Highest: 0.988 Model-6472 | Epoch 74 - Acc: 0.985 - Highest: 0.988 Model-6472 | Epoch 75 - Acc: 0.982 - Highest: 0.988 Model-6472 | Epoch 76 - Acc: 0.987 - Highest: 0.988 Model-6472 | Epoch 77 - Acc: 0.986 - Highest: 0.988 Model-6472 | Epoch 78 - Acc: 0.987 - Highest: 0.988 Model-6472 | Epoch 79 - Acc: 0.983 - Highest: 0.988 Model-6472 | Epoch 80 - Acc: 0.983 - Highest: 0.988 Model-6472 | Epoch 81 - Acc: 0.987 - Highest: 0.988 Model-6472 | Epoch 82 - Acc: 0.984 - Highest: 0.988 Model-6472 | Epoch 83 - Acc: 0.983 - Highest: 0.988 Model-6472 | Epoch 84 - Acc: 0.982 - Highest: 0.988 Model-6472 | Epoch 85 - Acc: 0.977 - Highest: 0.988 Model-6472 | Epoch 86 - Acc: 0.978 - Highest: 0.988 Model-6472 | Epoch 87 - Acc: 0.981 - Highest: 0.988 Model-6472 | Epoch 88 - Acc: 0.983 - Highest: 0.988 Model-6472 | ...training complete. Highest accuracy: 0.988.
Model achieved a validation accuracy of 98.8% at epoch 24. Plot below shows performace over full range of epochs.
vwr.plotAccHist(notLenet.name, notLenet.accHist())
Accuracy should very high for training data.
notLenet.test(trainingSigns.data())
Model-6472 | notLeNet restored. Model-6472 | Test accuracy: 1.000.
Model achieved a test accuracy of 96.5%.
notLenet.test(testSigns.data())
Model-6472 | notLeNet restored. Model-6472 | Test accuracy: 0.965.
To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.
You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.
### Load the images and plot them here.
### Feel free to use as many code cells as needed.
# traffic signs were downloaded from wikipedia
folder_name = 'traffic_signs/wikipedia/'
wiki_traffic_signs = TrafficSignsDataset (folder_name, n_classes)
vwr.imShowImages(wiki_traffic_signs.X)
TrafficSignsDataset-9536 | Loading signs from traffic_signs/wikipedia/... TrafficSignsDataset-9536 | Loaded 10,No passing for vehicles over 3.5 metric tons.png with label 10. TrafficSignsDataset-9536 | Loaded 19,Dangerous curve to the left.png with label 19. TrafficSignsDataset-9536 | Loaded 21,Double curve.png with label 21. TrafficSignsDataset-9536 | Loaded 22,Bumpy road.png with label 22. TrafficSignsDataset-9536 | Loaded 24,Road narrows on the right.png with label 24. TrafficSignsDataset-9536 | Loaded 26,Traffic signals.png with label 26. TrafficSignsDataset-9536 | Loaded 29,Bicycles crossing.png with label 29. TrafficSignsDataset-9536 | Loaded 3,Speed limit (60kmh).png with label 3. TrafficSignsDataset-9536 | Loaded 30,Beware of ice-snow.png with label 30. TrafficSignsDataset-9536 | Loaded 32,End of all speed and passing limits.png with label 32. TrafficSignsDataset-9536 | Loaded 35,Ahead only.png with label 35. TrafficSignsDataset-9536 | Loaded 40,Roundabout mandatory.png with label 40. TrafficSignsDataset-9536 | Loaded 41,End of no passing.png with label 41. TrafficSignsDataset-9536 | ...13 signs loaded.
### Run the predictions here and use the model to output the prediction for each image.
### Make sure to pre-process the images with the same pre-processing pipeline used earlier.
### Feel free to use as many code cells as needed.
wiki_traffic_signs.restoreOrgImages()
wiki_traffic_signs.processImages(image_processors)
TrafficSignsDataset-9536 | Original images and labels restored. TrafficSignsDataset-9536 | Processing images... TrafficSignsDataset-9536 | Applying equalizeHist() to images. TrafficSignsDataset-9536 | Applying RGB_to_norm() to images. TrafficSignsDataset-9536 | ...images processed.
### Calculate the accuracy for these 5 new images.
### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.
notLenet.test(wiki_traffic_signs.data())
Model-6472 | notLeNet restored. Model-6472 | Test accuracy: 1.000.
For each of the new images, print out the model's softmax probabilities to show the certainty of the model's predictions (limit the output to the top 5 probabilities for each image). tf.nn.top_k could prove helpful here.
The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.
tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.
Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. tf.nn.top_k is used to choose the three classes with the highest probability:
# (5, 6) array
a = np.array([[ 0.24879643, 0.07032244, 0.12641572, 0.34763842, 0.07893497,
0.12789202],
[ 0.28086119, 0.27569815, 0.08594638, 0.0178669 , 0.18063401,
0.15899337],
[ 0.26076848, 0.23664738, 0.08020603, 0.07001922, 0.1134371 ,
0.23892179],
[ 0.11943333, 0.29198961, 0.02605103, 0.26234032, 0.1351348 ,
0.16505091],
[ 0.09561176, 0.34396535, 0.0643941 , 0.16240774, 0.24206137,
0.09155967]])
Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:
TopKV2(values=array([[ 0.34763842, 0.24879643, 0.12789202],
[ 0.28086119, 0.27569815, 0.18063401],
[ 0.26076848, 0.23892179, 0.23664738],
[ 0.29198961, 0.26234032, 0.16505091],
[ 0.34396535, 0.24206137, 0.16240774]]), indices=array([[3, 0, 5],
[0, 1, 4],
[0, 5, 1],
[1, 3, 5],
[1, 4, 3]], dtype=int32))
Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web.
### Feel free to use as many code cells as needed.
predictions = notLenet.predict(wiki_traffic_signs.X, top=5)
vwr.imShowPredictions(notLenet.name, wiki_traffic_signs.org_X, predictions)
Model-6472 | notLeNet restored. Model-6472 | Classifying images... Model-6472 | ...13 images classified.
Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.
This Section is not required to complete but acts as an additional excersise for understaning the output of a neural network's weights. While neural networks can be a great learning device they are often referred to as a black box. We can understand what the weights of a neural network look like better by plotting their feature maps. After successfully training your neural network you can see what it's feature maps look like by plotting the output of the network's weight layers in response to a test stimuli image. From these plotted feature maps, it's possible to see what characteristics of an image the network finds interesting. For a sign, maybe the inner network feature maps react with high activation to the sign's boundary outline or to the contrast in the sign's painted symbol.
Provided for you below is the function code that allows you to get the visualization output of any tensorflow weight layer you want. The inputs to the function should be a stimuli image, one used during training or a new one you provided, and then the tensorflow variable name that represents the layer's state during the training process, for instance if you wanted to see what the LeNet lab's feature maps looked like for it's second convolutional layer you could enter conv2 as the tf_activation variable.
For an example of what feature map outputs look like, check out NVIDIA's results in their paper End-to-End Deep Learning for Self-Driving Cars in the section Visualization of internal CNN State. NVIDIA was able to show that their network's inner weights had high activations to road boundary lines by comparing feature maps from an image with a clear path to one without. Try experimenting with a similar test to show that your trained network's weights are looking for interesting features, whether it's looking at differences in feature maps from images with or without a sign, or even what feature maps look like in a trained network vs a completely untrained one on the same sign image.
Your output should look something like this (above)
### Visualize your network's feature maps here.
### Feel free to use as many code cells as needed.
# image_input: the test image being fed into the network to produce the feature maps
# tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific weight layer
# activation_min/max: can be used to view the activation contrast in more detail, by default matplot sets min and max to the actual min and max values of the output
# plt_num: used to plot out multiple different weight feature map sets on the same block, just extend the plt number for each new feature map entry
def outputFeatureMap(image_input, tf_activation, activation_min=-1, activation_max=-1 ,plt_num=1):
# Here make sure to preprocess your image_input in a way your network expects
# with size, normalization, ect if needed
# image_input =
# Note: x should be the same name as your network's tensorflow data placeholder variable
# If you get an error tf_activation is not defined it may be having trouble accessing the variable from inside a function
activation = tf_activation.eval(session=sess,feed_dict={x : image_input})
featuremaps = activation.shape[3]
plt.figure(plt_num, figsize=(15,15))
for featuremap in range(featuremaps):
plt.subplot(6,8, featuremap+1) # sets the number of feature maps to show on each row and column
plt.title('FeatureMap ' + str(featuremap)) # displays the feature map number
if activation_min != -1 & activation_max != -1:
plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin =activation_min, vmax=activation_max, cmap="gray")
elif activation_max != -1:
plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmax=activation_max, cmap="gray")
elif activation_min !=-1:
plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin=activation_min, cmap="gray")
else:
plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", cmap="gray")
x = trainingSigns.org_X[8500].copy()
equ = equalizeHist(x)
img = RGB_to_norm(equ)
plt.imshow(norm_to_RGB(img))
<matplotlib.image.AxesImage at 0x1f807594710>
layer_outputs = notLenet.eval_layer(0, img)
vwr.imShowConvOutputs(layer_outputs)
Model-6472 | Evaluating layer 0. Model-6472 | notLeNet restored. Model-6472 | Output shape: (1, 32, 32, 1).
layer_outputs = notLenet.eval_layer(1, img)
vwr.imShowConvOutputs(layer_outputs)
Model-6472 | Evaluating layer 1. Model-6472 | notLeNet restored. Model-6472 | Output shape: (1, 28, 28, 24).
Just out of curiosity, a multi-scale CNN is attempted.
A layer that concatenates flattened layers is required.
class Concatenate(Layer):
def setName(self):
self.name = "Concatenate"
return
def connect(self, *prev_layers):
self.model = prev_layers[0].model
tensors = [layer.tensor for layer in prev_layers]
self.tensor = tf.concat(tensors, axis=1)
return self
The architecture is similar to the one Sermanet and Lecunn described in "Traffic Sign Recognition with Multi-Scale Convolutional Networks" where the output of the first stage is fed to the classifier stage.
notSermanet = Model("notSermanet", image_shape, n_classes)
stage_1x1 = Conv2D ([32, 32, 1]).connect(notSermanet.inputLayer())
stage_1 = Conv2D ([28, 28, 24]).connect(stage_1x1)
stage_1 = Pooling([14, 14]).connect(stage_1)
flatten_1 = Flatten().connect(stage_1)
stage_2 = Conv2D ([10, 10, 64]).connect(stage_1)
stage_2 = Pooling([ 5, 5]).connect(stage_2)
stage_2 = Conv2D ([3, 3, 96]).connect(stage_2)
flatten_2 = Flatten().connect(stage_2)
stage_3 = Concatenate().connect(flatten_1, flatten_2)
stage_3 = Connected([240]).connect(stage_3)
stage_3 = Dropout().connect(stage_3)
stage_3 = Connected([168]).connect(stage_3)
stage_3 = Dropout().connect(stage_3)
notSermanet.connectLogits(stage_3)
notSermanet.train(trainingSigns.data(), validSigns.data(), batch_size=128,
epochs_done=64, acc_done=0.997, keep_prob=0.5)
Model-1552 | Training... Model-1552 | Epoch 1 - New High Acc: 0.943 Model-1552 | notSermanet saved. Model-1552 | Epoch 2 - New High Acc: 0.968 Model-1552 | notSermanet saved. Model-1552 | Epoch 3 - New High Acc: 0.979 Model-1552 | notSermanet saved. Model-1552 | Epoch 4 - Acc: 0.978 - Highest: 0.979 Model-1552 | Epoch 5 - New High Acc: 0.980 Model-1552 | notSermanet saved. Model-1552 | Epoch 6 - Acc: 0.980 - Highest: 0.980 Model-1552 | Epoch 7 - New High Acc: 0.981 Model-1552 | notSermanet saved. Model-1552 | Epoch 8 - New High Acc: 0.982 Model-1552 | notSermanet saved. Model-1552 | Epoch 9 - Acc: 0.974 - Highest: 0.982 Model-1552 | Epoch 10 - New High Acc: 0.985 Model-1552 | notSermanet saved. Model-1552 | Epoch 11 - Acc: 0.980 - Highest: 0.985 Model-1552 | Epoch 12 - Acc: 0.975 - Highest: 0.985 Model-1552 | Epoch 13 - Acc: 0.975 - Highest: 0.985 Model-1552 | Epoch 14 - Acc: 0.981 - Highest: 0.985 Model-1552 | Epoch 15 - Acc: 0.981 - Highest: 0.985 Model-1552 | Epoch 16 - Acc: 0.978 - Highest: 0.985 Model-1552 | Epoch 17 - New High Acc: 0.986 Model-1552 | notSermanet saved. Model-1552 | Epoch 18 - Acc: 0.974 - Highest: 0.986 Model-1552 | Epoch 19 - Acc: 0.985 - Highest: 0.986 Model-1552 | Epoch 20 - Acc: 0.983 - Highest: 0.986 Model-1552 | Epoch 21 - Acc: 0.986 - Highest: 0.986 Model-1552 | Epoch 22 - Acc: 0.984 - Highest: 0.986 Model-1552 | Epoch 23 - Acc: 0.980 - Highest: 0.986 Model-1552 | Epoch 24 - New High Acc: 0.988 Model-1552 | notSermanet saved. Model-1552 | Epoch 25 - Acc: 0.980 - Highest: 0.988 Model-1552 | Epoch 26 - Acc: 0.978 - Highest: 0.988 Model-1552 | Epoch 27 - Acc: 0.985 - Highest: 0.988 Model-1552 | Epoch 28 - Acc: 0.982 - Highest: 0.988 Model-1552 | Epoch 29 - Acc: 0.984 - Highest: 0.988 Model-1552 | Epoch 30 - Acc: 0.981 - Highest: 0.988 Model-1552 | Epoch 31 - Acc: 0.984 - Highest: 0.988 Model-1552 | Epoch 32 - Acc: 0.984 - Highest: 0.988 Model-1552 | Epoch 33 - Acc: 0.979 - Highest: 0.988 Model-1552 | Epoch 34 - Acc: 0.987 - Highest: 0.988 Model-1552 | Epoch 35 - Acc: 0.983 - Highest: 0.988 Model-1552 | Epoch 36 - Acc: 0.983 - Highest: 0.988 Model-1552 | Epoch 37 - Acc: 0.985 - Highest: 0.988 Model-1552 | Epoch 38 - Acc: 0.979 - Highest: 0.988 Model-1552 | Epoch 39 - Acc: 0.978 - Highest: 0.988 Model-1552 | Epoch 40 - Acc: 0.980 - Highest: 0.988 Model-1552 | Epoch 41 - Acc: 0.977 - Highest: 0.988 Model-1552 | Epoch 42 - Acc: 0.985 - Highest: 0.988 Model-1552 | Epoch 43 - Acc: 0.983 - Highest: 0.988 Model-1552 | Epoch 44 - Acc: 0.987 - Highest: 0.988 Model-1552 | Epoch 45 - Acc: 0.980 - Highest: 0.988 Model-1552 | Epoch 46 - Acc: 0.986 - Highest: 0.988 Model-1552 | Epoch 47 - Acc: 0.985 - Highest: 0.988 Model-1552 | Epoch 48 - Acc: 0.976 - Highest: 0.988 Model-1552 | Epoch 49 - Acc: 0.969 - Highest: 0.988 Model-1552 | Epoch 50 - Acc: 0.986 - Highest: 0.988 Model-1552 | Epoch 51 - Acc: 0.986 - Highest: 0.988 Model-1552 | Epoch 52 - Acc: 0.987 - Highest: 0.988 Model-1552 | Epoch 53 - Acc: 0.983 - Highest: 0.988 Model-1552 | Epoch 54 - Acc: 0.983 - Highest: 0.988 Model-1552 | Epoch 55 - Acc: 0.985 - Highest: 0.988 Model-1552 | Epoch 56 - Acc: 0.982 - Highest: 0.988 Model-1552 | Epoch 57 - Acc: 0.977 - Highest: 0.988 Model-1552 | Epoch 58 - Acc: 0.985 - Highest: 0.988 Model-1552 | Epoch 59 - Acc: 0.984 - Highest: 0.988 Model-1552 | Epoch 60 - Acc: 0.983 - Highest: 0.988 Model-1552 | Epoch 61 - New High Acc: 0.991 Model-1552 | notSermanet saved. Model-1552 | Epoch 62 - Acc: 0.985 - Highest: 0.991 Model-1552 | Epoch 63 - Acc: 0.988 - Highest: 0.991 Model-1552 | Epoch 64 - Acc: 0.986 - Highest: 0.991 Model-1552 | Epoch 65 - Acc: 0.983 - Highest: 0.991 Model-1552 | Epoch 66 - Acc: 0.985 - Highest: 0.991 Model-1552 | Epoch 67 - Acc: 0.981 - Highest: 0.991 Model-1552 | Epoch 68 - Acc: 0.985 - Highest: 0.991 Model-1552 | Epoch 69 - Acc: 0.979 - Highest: 0.991 Model-1552 | Epoch 70 - Acc: 0.985 - Highest: 0.991 Model-1552 | Epoch 71 - Acc: 0.988 - Highest: 0.991 Model-1552 | Epoch 72 - Acc: 0.982 - Highest: 0.991 Model-1552 | Epoch 73 - Acc: 0.983 - Highest: 0.991 Model-1552 | Epoch 74 - Acc: 0.988 - Highest: 0.991 Model-1552 | Epoch 75 - Acc: 0.983 - Highest: 0.991 Model-1552 | Epoch 76 - Acc: 0.983 - Highest: 0.991 Model-1552 | Epoch 77 - Acc: 0.983 - Highest: 0.991 Model-1552 | Epoch 78 - Acc: 0.982 - Highest: 0.991 Model-1552 | Epoch 79 - Acc: 0.984 - Highest: 0.991 Model-1552 | Epoch 80 - Acc: 0.983 - Highest: 0.991 Model-1552 | Epoch 81 - Acc: 0.978 - Highest: 0.991 Model-1552 | Epoch 82 - Acc: 0.980 - Highest: 0.991 Model-1552 | Epoch 83 - Acc: 0.987 - Highest: 0.991 Model-1552 | Epoch 84 - Acc: 0.981 - Highest: 0.991 Model-1552 | Epoch 85 - Acc: 0.986 - Highest: 0.991 Model-1552 | Epoch 86 - Acc: 0.981 - Highest: 0.991 Model-1552 | Epoch 87 - Acc: 0.989 - Highest: 0.991 Model-1552 | Epoch 88 - Acc: 0.983 - Highest: 0.991 Model-1552 | Epoch 89 - Acc: 0.981 - Highest: 0.991 Model-1552 | Epoch 90 - Acc: 0.977 - Highest: 0.991 Model-1552 | Epoch 91 - Acc: 0.970 - Highest: 0.991 Model-1552 | Epoch 92 - Acc: 0.984 - Highest: 0.991 Model-1552 | Epoch 93 - Acc: 0.980 - Highest: 0.991 Model-1552 | Epoch 94 - Acc: 0.980 - Highest: 0.991 Model-1552 | Epoch 95 - Acc: 0.984 - Highest: 0.991 Model-1552 | Epoch 96 - Acc: 0.982 - Highest: 0.991 Model-1552 | Epoch 97 - Acc: 0.968 - Highest: 0.991 Model-1552 | Epoch 98 - Acc: 0.979 - Highest: 0.991 Model-1552 | Epoch 99 - Acc: 0.978 - Highest: 0.991 Model-1552 | Epoch 100 - Acc: 0.981 - Highest: 0.991 Model-1552 | Epoch 101 - Acc: 0.981 - Highest: 0.991 Model-1552 | Epoch 102 - Acc: 0.987 - Highest: 0.991 Model-1552 | Epoch 103 - Acc: 0.981 - Highest: 0.991 Model-1552 | Epoch 104 - Acc: 0.984 - Highest: 0.991 Model-1552 | Epoch 105 - Acc: 0.983 - Highest: 0.991 Model-1552 | Epoch 106 - Acc: 0.976 - Highest: 0.991 Model-1552 | Epoch 107 - Acc: 0.980 - Highest: 0.991 Model-1552 | Epoch 108 - Acc: 0.982 - Highest: 0.991 Model-1552 | Epoch 109 - Acc: 0.983 - Highest: 0.991 Model-1552 | Epoch 110 - Acc: 0.978 - Highest: 0.991 Model-1552 | Epoch 111 - Acc: 0.974 - Highest: 0.991 Model-1552 | Epoch 112 - Acc: 0.982 - Highest: 0.991 Model-1552 | Epoch 113 - Acc: 0.981 - Highest: 0.991 Model-1552 | Epoch 114 - Acc: 0.981 - Highest: 0.991 Model-1552 | Epoch 115 - Acc: 0.979 - Highest: 0.991 Model-1552 | Epoch 116 - Acc: 0.978 - Highest: 0.991 Model-1552 | Epoch 117 - Acc: 0.969 - Highest: 0.991 Model-1552 | Epoch 118 - Acc: 0.977 - Highest: 0.991 Model-1552 | Epoch 119 - Acc: 0.979 - Highest: 0.991 Model-1552 | Epoch 120 - Acc: 0.981 - Highest: 0.991 Model-1552 | Epoch 121 - Acc: 0.979 - Highest: 0.991 Model-1552 | Epoch 122 - Acc: 0.979 - Highest: 0.991 Model-1552 | Epoch 123 - Acc: 0.979 - Highest: 0.991 Model-1552 | Epoch 124 - Acc: 0.983 - Highest: 0.991 Model-1552 | Epoch 125 - Acc: 0.970 - Highest: 0.991 Model-1552 | ...training complete. Highest accuracy: 0.991.
With a validation accuracy of 99.1% at epoch 61, the multi-scale CNN did a little better than the sequential model during training.
vwr.plotAccHist(notSermanet.name, notSermanet.accHist())
notSermanet.test(testSigns.data())
Model-1552 | notSermanet restored. Model-1552 | Test accuracy: 0.968.
notSermanet.test(wiki_traffic_signs.data())
Model-1552 | notSermanet restored. Model-1552 | Test accuracy: 1.000.
predictions = notSermanet.predict(wiki_traffic_signs.X, top=5)
vwr.imShowPredictions(notSermanet.name, wiki_traffic_signs.org_X, predictions)
Model-1552 | notSermanet restored. Model-1552 | Classifying images... Model-1552 | ...13 images classified.